var gragoverId = null;
var neighbor = null;
var list = document.getElementById("fieldList")
var registedWidgets = ['text','number','select','textarea','attachment','user'];

function handleOndragstart(e) {
	gragoverId = e.target.id;
	let widgetType = e.target.getAttribute("widgetType");
	e.dataTransfer.setData('widgetType', JSON.stringify({
		widgetType: widgetType
	}));
}

// function handleOndragover(e) {
// 	e.preventDefault();
// 	let ele = e.target;
// 	let i=0;
// 	do{
// 		let draggable = ele.getAttribute("draggable")
// 		if(!draggable){
// 			ele = ele.parentNode;
// 		}else{
// 			console.log("紧邻元素ID:",gragoverId)
// 			ele.style.border = "1px solid #336df4";
// 			neighbor = ele;
// 			break;
// 		}
// 		i++
// 	}while(i<5);
// }

// function handleOndragleave(e) {
// 	e.preventDefault();
// 	let ele = e.target;
// 	let i=0;
// 	do{
// 		let draggable = ele.getAttribute("draggable")
// 		if(!draggable){
// 			ele = ele.parentNode;
// 		}else{
// 			ele.style.border = "1px solid #fff";
// 			console.log("neighbor-> ",ele);
// 			break;
// 		}
// 		i++
// 	}while(i<5);
// }

function createWidget(widgetType,formDesigner){
	let widget = null;
	if (widgetType === "text") {
		widget=new TextWidget('form',formDesigner)
	}
	if (widgetType === "number") {
		widget=new NumberWidget('form',formDesigner)
	}
	if (widgetType === "select") {
		widget=new SelectWidget('form',formDesigner)
	}
	if (widgetType === "textarea") {
		widget=new TextAreaWidget('form',formDesigner)
	}
	if (widgetType === "attachment") {
		widget=new AttachmentWidget('form',formDesigner)
	}
	if (widgetType === "user") {
		widget=new UserWidget('form',formDesigner)
	}
	if (widgetType === "date") {
		widget=new DateWidget('form',formDesigner)
	}
	return widget;
}

// function handleOndrop(e) {
// 	console.log("父元素drop事件")
// 	let eventData = JSON.parse(e.dataTransfer.getData("widgetType"));
// 	let widgetType = eventData.widgetType;
// 	let sourceId = eventData.id;

// 	//来自货架的控件
// 	if (sourceId) {
// 		e.target.appendChild(document.getElementById(sourceId));
// 	} else {
// 		console.log("货架紧邻元素：",neighbor)
// 		let n = e.target;
// 		// if (widgetType === "text") {
// 		// 	n.appendChild(createWidget('form'))
// 		// }
// 		// if (widgetType === "number") {
// 		// 	n.appendChild(createWidget('form'))
// 		// }
// 		// if (widgetType === "select") {
// 		// 	n.appendChild(createWidget('form'))
// 		// }
// 		// if (widgetType === "textarea") {
// 		// 	n.appendChild(createWidget('form'))
// 		// }
// 		// if (widgetType === "attachment") {
// 		// 	n.appendChild(createWidget('form'))
// 		// }
// 		// if (widgetType === "user") {
// 		// 	n.appendChild(createWidget('form'))
// 		// }
		
// 		n.appendChild(createWidget(widgetType))
// 	}
// }

class Widget {
	constructor(source,formDesigner) {
		this.formDesiger = formDesigner;
		this.config = {};
		this.element = document.createElement("div");
		this.element.setAttribute("class", "widget");
		this.id = (new Date().getTime() + "").substring(7);
		this.element.setAttribute("id", this.id)
		this.element.setAttribute("draggable", true)
		this.element.setAttribute("source", source);
		//操作按钮组
		this.operationBar = document.createElement("div");
		this.operationBar.setAttribute("class", "field-item-operationBar");
		//复制按钮
		this.copyBtn = document.createElement("div");
		this.copyBtn.setAttribute("class", "copy-btn");
		this.copyBtn.innerText = "复制";
		this.operationBar.appendChild(this.copyBtn)
		//间隔符号
		this.space = document.createElement("div");
		this.space.innerText = "|";
		this.operationBar.appendChild(this.space)
		//删除按钮
		this.delBtn = document.createElement("div");
		this.delBtn.setAttribute("class", "del-btn");
		this.delBtn.innerText = "删除";
		this.delBtn.addEventListener("click", (e) => {
			this.element.parentNode.removeChild(this.element)
			//通知给设计器
			this.formDesiger.removeWidget(this);
		})
		this.operationBar.appendChild(this.delBtn)
		//安装按钮组
		this.element.appendChild(this.operationBar)

		//控件内容
		this.initElement();

		//开始拖拽事件
		this.element.addEventListener("dragstart", (e) => {
			gragoverId = e.target.id;
			console.log("组件dragstart事件")
			//将当前对象作为参数传递给容器
			e.dataTransfer.setData('widgetType', JSON.stringify({
				id: this.id
			}));
		})
		//目标上方悬停事件
		this.element.addEventListener("dragover", (e) => {
			console.log("组件dragover事件")
			e.target.style.border = "1px solid transparent";
		})
		//鼠标松开事件
		this.element.addEventListener("drop", (e) => {
			console.log("组件drop事件")
			e.stopPropagation();
			if(gragoverId){
				let gragoverEle = document.getElementById(gragoverId);
				this.element.before(gragoverEle);
				gragoverId = null;
				return;
			}
			if(neighbor){
				let eventData = JSON.parse(e.dataTransfer.getData("widgetType"));
				let widgetType = eventData.widgetType;
				let widget = createWidget(widgetType,this.formDesiger);
				this.element.before(widget.getElement())
				this.formDesiger.insertBefore(widget,this)
				neighbor=null;
				return;
			}
		})

		//点击展示操作按钮事件
		this.element.addEventListener("click", (e) => {
			this.active();
			configPanel.show(this)
		})
	}
	
	setId(id){
		this.id = id;
		this.element.setAttribute("id", id)
	}
	
	getId(){
		return this.id;
	}
	
	initElement() {
		this.label = this.createLabel();
		this.formItemContent = this.createContent();
		this.formItemBox = div('form-item-box ' + this.formItemContent.getAttribute("class"), [this.label, this
			.formItemContent
		]);
		this.element.appendChild(this.formItemBox);
	}

	createLabel() {
		this.label = document.createElement("div");
		this.labelText = span('labelText', '数值')
		this.label.appendChild(this.labelText);
		this.required = span('required', '*')
		this.required.style.display = "none";
		this.label.appendChild(this.required)
		return this.label;
	}
	createContent() {
		let ele = document.createElement("div");
		ele.setAttribute("class", "inline");
		this.input = div('placeholder', '请输入');
		return div('inline', this.input);
	}

	setConfig(config) {
		this.config = config;
		console.log("刷新组件属性：",config)
		this.setId(this.config.id);
		//刷新组件
		this.setLabel(this.config.title)
		//更新组件提示语
		this.setPlaceholder(this.config.placeholder);
		//设置必填
		this.setRequired(this.config.required);
	}

	setPlaceholder(placeholder) {

	}

	setRequired(required) {
		if (required) {
			this.required.style.display = "inline-block";
		} else {
			this.required.style.display = "none";
		}
	}

	//后期考虑让子元素实现设置属性值模块
	setLabel(label) {
		this.labelText.innerText = label;
	}

	getConfig() {
		return this.config;
	}

	getOperationBar() {
		return this.operationBar;
	}

	active() {
		//关闭其他组件的选中状态
		let widgets = document.getElementsByClassName("widget");
		for (var i = 0; i < widgets.length; i++) {
			let w = widgets[i]
			let operationBar = w.firstChild;
			w.style.border = "1px solid #fff";
			operationBar.style.display = "none";
		}
		this.operationBar.style.display = "flex"
		this.element.style.border = "1px solid #336df4"
	}

	getElement() {
		return this.element;
	}
}


class NumberWidget extends Widget {
	constructor(source,formDesigner) {
		super(source,formDesigner)
		this.config = {
			widgetType:"number",
			title: "数值",
			placeholder: "请输入数值",
			print: true,
			required: false,
			defaultValue: {
				enable: false,
				value: null
			}
		}
	}
	getConfig() {
		return this.config;
	}

	setLabel(label) {
		this.labelText.innerText = label;
	}
	createLabel() {
		this.label = document.createElement("div");
		this.labelText = span('labelText', '数值')
		this.label.appendChild(this.labelText);
		this.required = span('required', '*')
		this.required.style.display = "none";
		this.label.appendChild(this.required)
		return this.label;
	}

	setRequired(required) {
		if (required) {
			this.required.style.display = "inline-block";
		} else {
			this.required.style.display = "none";
		}
	}
	createContent() {
		let ele = document.createElement("div");
		ele.setAttribute("class", "inline");
		this.placeholder = div('placeholder', "请输入数值");
		return div('inline', this.placeholder);
	}

	setPlaceholder(placeholder) {
		this.placeholder.innerText = placeholder;
	}

	getElement() {
		return this.element;
	}
}

class TextWidget extends Widget {
	constructor(source,formDesigner) {
		super(source,formDesigner)
		this.config = {
			widgetType:"text",
			title: "文本",
			placeholder: "请输入",
			print: true,
			required: false,
			defaultValue: {
				enable: false,
				value: null
			}
		}
	}
	getConfig() {
		return this.config;
	}
	createLabel() {
		this.label = document.createElement("div");
		this.labelText = span('labelText', '文本')
		this.label.appendChild(this.labelText);
		this.required = span('required', '*')
		this.required.style.display = "none";
		this.label.appendChild(this.required)
		return this.label;
	}
	setLabel(label) {
		this.labelText.innerText = label;
	}
	setRequired(required) {
		if (required) {
			this.required.style.display = "inline-block";
		} else {
			this.required.style.display = "none";
		}
	}
	createContent() {
		let ele = document.createElement("div");
		ele.setAttribute("class", "inline");
		this.placeholder = div('placeholder', '请输入')
		return div('inline', this.placeholder);
	}

	setPlaceholder(placeholder) {
		this.placeholder.innerText = placeholder;
	}

	getElement() {
		return this.element;
	}
}

class TextAreaWidget extends Widget {
	constructor(source,formDesigner) {
		super(source,formDesigner)
		this.config = {
			widgetType:"textarea",
			title: "长文本",
			placeholder: "请输入",
			print: true,
			required: false,
			defaultValue: {
				enable: false,
				value: null
			}
		}
	}
	getConfig() {
		return this.config;
	}
	createLabel() {
		this.label = document.createElement("div");
		this.labelText = span('labelText', '长文本')
		this.label.appendChild(this.labelText);
		this.required = span('required', '*')
		//this.required.style.display="none";
		this.label.appendChild(this.required)
		return this.label;
	}

	setLabel(label) {
		this.labelText.innerText = label;
	}

	setRequired(required) {
		if (required) {
			this.required.style.display = "inline-block";
		} else {
			this.required.style.display = "none";
		}
	}
	createContent() {
		this.placeholder = span('base-textarea', '请输入');
		return div('', this.placeholder);
	}

	setPlaceholder(placeholder) {
		this.placeholder.innerText = placeholder;
	}

	getElement() {
		return this.element;
	}
}

class SelectWidget extends Widget {
	constructor(arg) {
		super(arg)
		this.config = {
			widgetType:"select",
			title: "单选",
			placeholder: "",
			options: {
				dataSource: '手动添加',
				fixedValues: [
					
				],
				dataSourceApi:{
					url:null,
					token:null,
					key:null
				}
			},
			print: true,
			required: false,
			defaultValue: {
				enable: false,
				value: null
			}
		}
	}
	getConfig() {
		return this.config;
	}
	createLabel() {
		this.label = document.createElement("div");
		this.labelText = span('labelText', '下拉选项')
		this.label.appendChild(this.labelText);
		this.required = span('required', '*')
		this.required.style.display = "none";
		this.label.appendChild(this.required)
		return this.label;
	}
	createContent() {
		let ele = document.createElement("div");
		ele.setAttribute("class", "inline");
		return div('inline', div('placeholder', '请选择>'));
	}

	getElement() {
		return this.element;
	}
}

class AttachmentWidget extends Widget {
	constructor(source,formDesigner) {
		super(source,formDesigner)
		this.config = {
			widgetType:"attachment",
			title: "附件",
			placeholder: "",
			print: true,
			required: false,
			defaultValue: {
				enable: false,
				value: null
			}
		}
	}
	getConfig() {
		return this.config;
	}
	createLabel() {
		this.label = document.createElement("div");
		this.labelText = span('labelText', '附件')
		this.label.appendChild(this.labelText);
		this.required = span('required', '*')
		this.required.style.display = "none";
		this.label.appendChild(this.required)
		return this.label;
	}
	createContent() {
		let element = document.createElement("div")
		element.setAttribute("class", "upload-btn")
		element.appendChild(span('icon', '+'))
		return element;
	}

	getElement() {
		return this.element;
	}
}

class UserWidget extends Widget{
	constructor(source,formDesigner) {
		super(source,formDesigner)
		this.config = {
			widgetType:"user",
			title: "联系人",
			placeholder: "",
			print: true,
			required: false,
			defaultValue: {
				enable: false,
				value: null
			}
		}
	}
	getConfig() {
		return this.config;
	}
	createLabel() {
		this.label = document.createElement("div");
		this.labelText = span('labelText', '联系人')
		this.label.appendChild(this.labelText);
		this.required = span('required', '*')
		this.required.style.display = "none";
		this.label.appendChild(this.required)
		return this.label;
	}
	createContent() {
		let element = document.createElement("div")
		element.setAttribute("class", "user-add-btn")
		element.appendChild(span('icon', '+'))
		console.log(element)
		return element;
	}
	
	getElement() {
		return this.element;
	}
}

class DateWidget extends Widget {
	constructor(source,formDesigner) {
		super(source,formDesigner)
		this.config = {
			widgetType:"date",
			title: "日期",
			placeholder: "请选择",
			print: true,
			required: false,
			defaultValue: {
				enable: false,
				value: null
			}
		}
	}
	getConfig() {
		return this.config;
	}
	setConfig(config){
		this.config = config;
	}
	createLabel() {
		this.label = document.createElement("div");
		this.labelText = span('labelText', '日期')
		this.label.appendChild(this.labelText);
		this.required = span('required', '*')
		this.required.style.display = "none";
		this.label.appendChild(this.required)
		return this.label;
	}
	setLabel(label) {
		this.labelText.innerText = label;
	}
	setRequired(required) {
		if (required) {
			this.required.style.display = "inline-block";
		} else {
			this.required.style.display = "none";
		}
	}
	createContent() {
		let ele = document.createElement("div");
		ele.setAttribute("class", "inline");
		this.placeholder = div('placeholder', '请选择')
		return div('inline', this.placeholder);
	}

	setPlaceholder(placeholder) {
		this.placeholder.innerText = placeholder;
	}

	getElement() {
		return this.element;
	}
}
/**
 * 表单设计器
 * 
 * @author 李飞飞
 * @date 于2024年8月7日
 * @concat flysli@163.com
 */
class FormDesiger{
	constructor(el) {
		if(!el){
			alert("初始化表单设计器失败，原因：id为 ‘"+el+"’的元素不存在")
			throw new Error("初始化表单设计器失败，原因：id为 ‘"+el+"’的元素不存在");
		}
		
		/** 表单容器 **/
	    this.widgetArray = [];
		/** 设计器dom对象 **/
		this.element = document.createElement("div");
		this.element.setAttribute("id","fieldList");
		this.element.setAttribute("class","field-list");
		//设置标题
		// <div class="field-list-header">收款单</div>
		this.element.appendChild(div('field-list-header','收款单'))
		//初始化事件监听器
		this.initEventListeners();
		
		//将对象挂在到dom上
		document.getElementById(el).appendChild(this.element);
	}
	
	addWidget(widget){
		if(!widget){
			throw new Error("widget 不可以为空")
		}
		this.element.appendChild(widget.getElement())
		this.widgetArray.push(widget);
	}
	
	insertBefore(widget,beforeWidget){
		let beforeIndex = this.widgetArray.indexOf(beforeWidget);
		this.widgetArray.splice(beforeIndex,0,widget);
	}
	
	getWidgetArray(){
		return this.widgetArray;
	}
	
	removeWidget(widget){
		this.widgetArray=this.widgetArray.filter(function (value) {
			console.log(value,widget)
		  return value !== widget;
		});
	}
	
	initEventListeners(){
		// 初始化放入事件
		this.element.addEventListener("dragover",(e)=>{
			e.preventDefault();
			let ele = e.target;
			let i=0;
			console.log("设计器dragover事件")
			do{
				let draggable = ele.getAttribute("draggable")
				if(!draggable){
					ele = ele.parentNode;
				}else{
					ele.style.border = "1px solid #336df4";
					neighbor = ele;
					break;
				}
				i++
			}while(i<5);
		})
		
		//初始化ondragleave鼠标离开事件
		this.element.addEventListener("dragleave",(e)=>{
			e.preventDefault();
			let ele = e.target;
			let i=0;
			console.log("设计器dragleave事件")
			do{
				let draggable = ele.getAttribute("draggable")
				if(!draggable){
					ele = ele.parentNode;
				}else{
					ele.style.border = "1px solid #fff";
					console.log("neighbor-> ",ele);
					break;
				}
				i++
			}while(i<5);
		})
		
		/// 初始化放入事件
		this.element.addEventListener("drop",(e)=>{
			console.log("设计器drop事件")
			let eventData = JSON.parse(e.dataTransfer.getData("widgetType"));
			let widgetType = eventData.widgetType;
			let sourceId = eventData.id;
			//位置挪动
			if (sourceId) {
				e.target.appendChild(document.getElementById(sourceId));
			} else {
				let widget = createWidget(widgetType,this);
				this.addWidget(widget);
			}
		})
	}
	
	getFormJson(){
		let formJsonArray = [];
		for (var i = 0; i < this.getWidgetArray().length; i++) {
			let wa = this.getWidgetArray()[i];
			let config = wa.getConfig();
			config.id = wa.getId();
			formJsonArray.push(config)
		}
		return formJsonArray;
	}
}
var formDesiger = new FormDesiger("formDesigerContainer");
var formContainer = document.getElementById("fieldList");

function getJson(){
	console.log(JSON.stringify(formDesiger.getFormJson()))
}

var formJson = [{"widgetType":"text","title":"姓名","placeholder":"请输入","print":true,"required":false,"defaultValue":{"enable":false,"value":null},"id":"651437"},{"widgetType":"number","title":"年龄","placeholder":"请输入数值","print":true,"required":false,"defaultValue":{"enable":false,"value":null},"id":"652974"},{"widgetType":"textarea","title":"家庭住址","placeholder":"请输入","print":true,"required":false,"defaultValue":{"enable":false,"value":null},"id":"653923"},{"widgetType":"attachment","title":"身份证照片","placeholder":"","print":true,"required":false,"defaultValue":{"enable":false,"value":null},"id":"656690"},{"widgetType":"date","title":"出生日期","placeholder":"请选择","print":true,"required":false,"defaultValue":{"enable":false,"value":null},"id":"411727"},{"widgetType":"user","title":"监护人","placeholder":"","print":true,"required":false,"defaultValue":{"enable":false,"value":null},"id":"661558"},{"widgetType":"select","title":"学历","placeholder":"","options":{"dataSource":"手动添加","fixedValues":["初中","高中","大学"],"dataSourceApi":{"url":null,"token":null,"key":null}},"print":true,"required":false,"defaultValue":{"enable":false,"value":null}}]
//初始化form表单
// for (var i = 0; i < formJson.length; i++) {
// 	let widgetJson = formJson[i]
// 	let widgetType = widgetJson.widgetType;
// 	let widget = createWidget(widgetType,formDesiger);
// 	widget.setConfig(widgetJson);
// 	formDesiger.addWidget(widget);
// }